package com.hyp.pay.UI.Zxing.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Vibrator;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.hyp.pay.R;
import com.hyp.pay.UI.Home.activity.EditActivity;
import com.hyp.pay.UI.Home.activity.EditPaymentActivity;
import com.hyp.pay.UI.Home.activity.HomeActivity;
import com.hyp.pay.UI.Home.activity.WebViewActivity;
import com.hyp.pay.UI.Zxing.presenter.TestScanPresenter;
import com.hyp.pay.UI.Zxing.presenter.contract.TestScanContract;
import com.hyp.pay.base.BaseActivity;
import com.hyp.pay.http.Constants;
import com.hyp.pay.http.HyqApis;
import com.hyp.pay.model.JsonModel;
import com.hyp.pay.utils.SPUtil;
import com.hyp.pay.utils.SystemUtil;
import com.hyp.pay.weight.ProgressDialog;

import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.OnClick;
import cn.bingoogolapple.photopicker.activity.BGAPhotoPickerActivity;
import cn.bingoogolapple.qrcode.core.QRCodeView;
import cn.bingoogolapple.qrcode.zxing.QRCodeDecoder;
import cn.bingoogolapple.qrcode.zxing.ZXingView;


public class TestScanActivity extends BaseActivity<TestScanPresenter> implements TestScanContract.View, QRCodeView.Delegate {

    private static final int REQUEST_CODE_CHOOSE_QRCODE_FROM_GALLERY = 666;
    private int PHOTO_REQUEST_TAKEPHOTO = 0x2;

    private String mCharge;
    private String mUserid;
    private String order;
    private int orderid;
    private Long time2;

    private ProgressDialog mDialog;

    @BindView(R.id.zxingview)
    ZXingView mZxingview;

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_test_scan;
    }

    @Override
    protected void initView() {

        mCharge = getIntent().getStringExtra("charge");
        mUserid = getIntent().getStringExtra("userid");

        mZxingview.setDelegate(this);

        mDialog = new ProgressDialog(this);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, PHOTO_REQUEST_TAKEPHOTO);
        }
    }


    @Override
    protected void onStart() {
        super.onStart();
        mZxingview.startCamera();

        mZxingview.showScanRect();
        mZxingview.startSpot();
    }

    @Override
    protected void onStop() {
        mZxingview.stopCamera();
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        mZxingview.onDestroy();
        super.onDestroy();
    }


    @OnClick({R.id.button, R.id.button_back})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.button:
                startActivityForResult(BGAPhotoPickerActivity.newIntent(this, null, 1, null, false), REQUEST_CODE_CHOOSE_QRCODE_FROM_GALLERY);
                break;
            case R.id.button_back:
                finish();
                break;
        }
    }

    @Override
    public void showError(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        mZxingview.showScanRect();

        if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_CODE_CHOOSE_QRCODE_FROM_GALLERY) {
            final String picturePath = BGAPhotoPickerActivity.getSelectedImages(data).get(0);

            /*
            这里为了偷懒，就没有处理匿名 AsyncTask 内部类导致 Activity 泄漏的问题
            请开发在使用时自行处理匿名内部类导致Activity内存泄漏的问题，处理方式可参考 https://github.com/GeniusVJR/LearningNotes/blob/master/Part1/Android/Android%E5%86%85%E5%AD%98%E6%B3%84%E6%BC%8F%E6%80%BB%E7%BB%93.md
             */
            new AsyncTask<Void, Void, String>() {
                @Override
                protected String doInBackground(Void... params) {
                    return QRCodeDecoder.syncDecodeQRCode(picturePath);
                }

                @Override
                protected void onPostExecute(String result) {
                    if (TextUtils.isEmpty(result)) {
                        Toast.makeText(TestScanActivity.this, "未发现二维码", Toast.LENGTH_SHORT).show();
                    } else {
                        Log.i("olj", "成功++++++result:" + result);
//                        Toast.makeText(TestScanActivity.this, result, Toast.LENGTH_SHORT).show();
//                        setResult(0x2, new Intent().putExtra("result", result));
//                        finish();
                    }
                }
            }.execute();
        }
    }

    private void vibrate() {
        Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
        vibrator.vibrate(200);
    }

    @Override
    public void onScanQRCodeSuccess(String result) {
        Log.i("olj", "result:" + result);
        vibrate();
//        mZxingview.startSpot();

        String charge = mCharge;

        SPUtil.setCharge(charge);
        String newCharge = "";

        if (!TextUtils.isEmpty(charge)) {
            newCharge = SystemUtil.yuan2fen(charge);
        }

        String num = result.substring(0, 1);
        Log.i("olj", num);
        Log.i("olj", newCharge);
        if (!TextUtils.isEmpty(result)) {
            mZxingview.stopSpot();
            if (!TextUtils.isEmpty(num)) {
                if (num.equals("1")) {
                    mDialog.show();
                    mDialog.setText("收款中.....");
                    mPresenter.getWeixin("万众宝收款", newCharge, "1494594308", "1", mUserid, result, "127.0.0.1");
                } else if (num.equals("2")) {
                    mDialog.show();
                    mDialog.setText("收款中.....");
                    mPresenter.getZhiPay("万众宝收款", newCharge, "1494594308", "1", mUserid, result, "127.0.0.1");
                } else if (num.equals("3")) {
                    mDialog.show();
                    mDialog.setText("收款中.....");
                    mPresenter.getBaiDu("万众宝收款", newCharge, "2", "127.0.0.1", result, mUserid);
                } else if (num.equals("9")) {
                    mDialog.show();
                    mDialog.setText("收款中.....");
                    mPresenter.getQQPay(newCharge, result, "127.0.0.1", mUserid);
                }
            }
        }

    }

    @Override
    public void onScanQRCodeOpenCameraError() {
        showError("打开相机出错");
    }

    @Override
    public void showWeixin(String data) {
        {
            try {
                JSONObject jsonObject = new JSONObject(data);
                Log.i("olj", data);
                String code = jsonObject.getString("result_code");
                String msg = jsonObject.getString("return_msg");
                final String transaction_id = jsonObject.getString("transaction_id");
                order = transaction_id;
                Log.i("olj", code);
                if (code.equals("1001")) {
                    Log.i("olj", jsonObject.getString("return_msg"));
                    Toast.makeText(this, jsonObject.getString("return_msg"), Toast.LENGTH_SHORT).show();
                } else if (code.equals("0000")) {
                    mDialog.dismiss();
                    SPUtil.setOrder(transaction_id);
                    Toast.makeText(mContext, jsonObject.getString("return_msg"), Toast.LENGTH_SHORT).show();

                    Intent intent = new Intent(mContext, EditPaymentActivity.class);
                    startActivity(intent);
                    finish();

                } else if (code.equals("USERPAYING")) {
                    Toast.makeText(mContext, jsonObject.getString("return_msg"), Toast.LENGTH_SHORT).show();
                    if (msg.equals("需要用户输入支付密码")) {
                        orderid = 1;
                        mPresenter.getTimber();
                    }

                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }

    @Override
    public void showZhiPay(String data) {
        {
            try {
                JSONObject jsonObject = new JSONObject(data);
                Log.i("olj", data);
                String code = jsonObject.getString("result_code");
                String msg = jsonObject.getString("return_msg");
                final String transaction_id = jsonObject.getString("transaction_id");
                order = transaction_id;
                Log.i("olj", code);
                if (code.equals("1001")) {
                    Log.i("olj", jsonObject.getString("return_msg"));
                    Toast.makeText(this, jsonObject.getString("return_msg"), Toast.LENGTH_SHORT).show();
                } else if (code.equals("10000")) {
                    mDialog.dismiss();

                    SPUtil.setOrder(transaction_id);
                    Intent intent = new Intent(mContext, EditPaymentActivity.class);
                    startActivity(intent);
                    finish();
                } else if (code.equals("USERPAYING")) {
                    Toast.makeText(mContext, jsonObject.getString("return_msg"), Toast.LENGTH_SHORT).show();
                } else if (msg.equals("需要用户输入支付密码")) {
                    orderid = 2;
                    mPresenter.getTimber();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }

    @Override
    public void showBaiDu(String data) {
        {
            try {
                JSONObject jsonObject = new JSONObject(data);
                Log.i("olj", data);
                String code = jsonObject.getString("ret");
                final String msg = jsonObject.getString("msg");
                String content = jsonObject.getString("content");
                JSONObject jsonObject2 = new JSONObject(content);
                String order_no=jsonObject2.getString("order_no");
                order = order_no;
                Log.i("olj", code);
               if (code.equals("0") && msg.equals("OK")) {
                    mDialog.dismiss();
                    SPUtil.setOrder(order_no);
                    Intent intent2 = new Intent(mContext, EditPaymentActivity.class);
                    startActivity(intent2);
                   finish();
                } else if (msg.equals("需要用户输入支付密码")) {
                    orderid = 3;

                    mPresenter.getTimber();

//                webView.loadUrl(Host+"app_systemFall.html");
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void showJDPay(JsonModel data) {
        Toast.makeText(mContext, data.getReturn_msg(), Toast.LENGTH_SHORT).show();
    }

    @Override
    public void showQQPay(String data) {
        {

            try {
                JSONObject jsonObject = new JSONObject(data);
                Log.i("olj", data);
                String result_code = jsonObject.getString("result_code");
                String return_code = jsonObject.getString("return_code");
                final String return_msg = jsonObject.getString("return_msg");
                String transaction_id = jsonObject.getString("transaction_id");
                order = transaction_id;
                Log.i("olj", result_code);
                if (result_code.equals("SUCCESS") && return_code.equals("SUCCESS")) {

                    mDialog.dismiss();
                    SPUtil.setOrder(transaction_id);
                    Intent intent = new Intent(mContext, EditPaymentActivity.class);
                    startActivity(intent);
                    finish();
                } else if (return_msg.equals("需要用户输入支付密码")) {
                    orderid = 4;
                    mPresenter.getTimber();
                } else {
//                webView.loadUrl(Host+"app_systemFall.html");
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }

    @Override
    public void showWeixinOrder(String data) {
        try {
            JSONObject jsonObject = new JSONObject(data);
            Log.i("olj", data);
            String code = jsonObject.getString("trade_state");
            String transaction_id = jsonObject.getString("out_trade_no");
            Log.i("olj", code);
            if (time2 < 10) {
                if (code.equals("SUCCESS")) {

                    mDialog.dismiss();
                    SPUtil.setOrder(transaction_id);
                    Intent intent = new Intent(mContext, EditPaymentActivity.class);
                    startActivity(intent);
                    //取消订阅，停止执行
                    mPresenter.dispose();
                    finish();
                } else if (code.equals("USERPAYING")) {
//                Toast.makeText(mContext,jsonObject.getString("return_msg"), Toast.LENGTH_SHORT).show();
                }
            } else if (time2 == 10 && code.equals("USERPAYING")) {
                Toast.makeText(mContext, "对方取消支付", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(mContext, HomeActivity.class);
                intent.putExtra(Constants.WEB_VIEW_URL_PATH, HyqApis.HOST + "app_index.html");
                startActivity(intent);
//                webView.loadUrl(Host+"app_index.html");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void showZhifuOrder(String data) {

        try {
            JSONObject jsonObject = new JSONObject(data);
            Log.i("olj", data);
            String code = jsonObject.getString("trade_state");
            String transaction_id = jsonObject.getString("out_trade_no");
            Log.i("olj", code);
            if (time2 < 10) {
                if (code.equals("SUCCESS")) {

                    mDialog.dismiss();
                    SPUtil.setOrder(transaction_id);
                    Intent intent = new Intent(mContext, EditPaymentActivity.class);
                    startActivity(intent);
                    mPresenter.dispose();
                    finish();
                }
            } else if (time2 == 10 && code.equals("USERPAYING")) {
                Toast.makeText(mContext, "对方取消支付", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(mContext, HomeActivity.class);
                intent.putExtra(Constants.WEB_VIEW_URL_PATH, HyqApis.HOST + "app_index.html");
                startActivity(intent);
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void showBaiduOrder(String data) {
        {
            try {
                JSONObject jsonObject = new JSONObject(data);
                Log.i("olj", data);
                String code = jsonObject.getString("trade_state");
                String transaction_id = jsonObject.getString("out_trade_no");
                Log.i("olj", code);
                if (time2 < 10) {
                    if (code.equals("SUCCESS")) {

                        mDialog.dismiss();
                        SPUtil.setOrder(transaction_id);
                        Intent intent = new Intent(mContext, EditPaymentActivity.class);
                        startActivity(intent);
                        mPresenter.dispose();
                        finish();
                    }
                } else if (time2 == 10 && code.equals("USERPAYING")) {
                    Toast.makeText(mContext, "对方取消支付", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(mContext, HomeActivity.class);
                    intent.putExtra(Constants.WEB_VIEW_URL_PATH, HyqApis.HOST + "app_index.html");
                    startActivity(intent);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void showQQOrder(String data) {
        {
            try {
                JSONObject jsonObject = new JSONObject(data);
                Log.i("olj", data);
                String code = jsonObject.getString("trade_state");
                String transaction_id = jsonObject.getString("out_trade_no");
                Log.i("olj", code);
                if (time2 < 10) {
                    if (code.equals("SUCCESS")) {

                        mDialog.dismiss();
                        SPUtil.setOrder(transaction_id);
                        Intent intent = new Intent(mContext, EditPaymentActivity.class);
                        startActivity(intent);
                        mPresenter.dispose();
                        finish();
                    }
                } else if (time2 == 10 && code.equals("USERPAYING")) {
                    Toast.makeText(mContext, "对方取消支付", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(mContext, HomeActivity.class);
                    intent.putExtra(Constants.WEB_VIEW_URL_PATH, HyqApis.HOST + "app_index.html");
                    startActivity(intent);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void showTimber(Long time) {
        {
            time2 = time;
            Log.i("olj", time.toString());
            Log.i("olj", String.valueOf(orderid));
            if (orderid == 1) {
                mPresenter.getWeixinOrder(order);
            } else if (orderid == 2) {
                mPresenter.getZhifuOrder(order);
            } else if (orderid == 3) {
                mPresenter.getBaiduOrder(order);
            } else if (orderid == 4) {
                mPresenter.getQQOrder(order, "127.0.0.1");
            }

        }
    }
}
